import UpdateScore, {
  UpdateScoreMethods,
} from '@/pages/Teacher/ManageScore/components/UpdateScore';
import {
  deleteScoreUsingDelete,
  listScoresToTeacherUsingPost,
} from '@/services/student-management-system/fenshumokuai';
import { SearchOutlined } from '@ant-design/icons';
import { Badge, Button, Form, Input, message, Modal, Space, Table } from 'antd';

import {
  AntdStatus,
  getTagStatusByStatus,
  getTextByStatus,
} from '@/common/ScoreStatus';
import { useModel } from '@@/exports';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

const ManageScore: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  const initSearchParam = {
    current: 1,
    pageSize: 6,
    sortField: 'createTime',
    sortOrder: 'desc',
    teacherId: currentUser?.id ?? 0,
  };

  const [queryParam, setQueryParam] = useState<API.QueryScoreDTO>({ ...initSearchParam });
  const [dataSource, setDataSource] = useState<API.ScoreVO[]>([]);
  const [open, setOpen] = useState<boolean>(false);
  const [editScore, setEditScore] = useState<API.UpdateScoreDTO>({});
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [title, setTitle] = useState<string>('');
  const [total, setTotal] = useState<number>(0);
  const childRef = useRef<UpdateScoreMethods>(null);

  const handleOnEdit = (record: API.ScoreVO) => {
    // 如果成绩审核中，不能点击编辑
    // if (record.status === ScoreStatus.REVIEWING) {
    //   message.warning('成绩审核中，不能编辑');
    //   return;
    // }
    setTitle('编辑成绩');
    setEditScore({ ...record });
    setOpen(true);
  };

  const handleOnDelete = async (record: API.ScoreVO) => {
    const res = await deleteScoreUsingDelete({ id: record.id ?? -1 });
    if (res.code === 200) {
      message.success('删除成功');
      // 这里进行处理
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      await getScoreList();
    } else {
      message.error('删除失败：' + res.msg);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '学生', dataIndex: 'studentName', key: 'studentName' },
    { title: '班级', dataIndex: 'className', key: 'className' },
    { title: '课程名称', dataIndex: 'courseName', key: 'courseName' },
    { title: '分数', dataIndex: 'score', key: 'score' },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (text: number) => (
        <Badge status={getTagStatusByStatus(text) as AntdStatus} text={getTextByStatus(text)} />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: (text: Date) => (
        <>
          <div>{moment(text).format('YYYY-MM-DD')}</div>
          <div>{moment(text).format('HH:mm:ss')}</div>
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'options',
      render: (_: any, record: any) => (
        <Space>
          <Button size="small" onClick={() => handleOnEdit(record)}>
            编辑
          </Button>
          <Button size="small" danger onClick={() => handleOnDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const getScoreList = async () => {
    const res = await listScoresToTeacherUsingPost(queryParam);
    if (res.code === 200) {
      message.success('获取数据成功');
      setDataSource(res.data?.records ?? []);
      setTotal(res.data?.total ?? 0);
    } else {
      message.error('获取数据失败：' + res.msg);
    }
  };

  const handleOk = async () => {
    setConfirmLoading(true);

    try {
      // 调用子组件的方法进行表单提交
      const success = await childRef.current?.submitForm();
      if (success) {
        setOpen(false); // 如果提交成功则关闭Modal
        getScoreList(); // 刷新列表
      }
    } catch (error) {
      message.error('提交数据有误，请检查后再提交');
    } finally {
      setConfirmLoading(false); // 无论成功还是失败都应重置loading状态
    }
  };

  const handleCancel = () => {
    childRef.current?.handleReset();
    setOpen(false);
  };

  const handleAddClass = () => {
    setTitle('新增成绩');
    setEditScore({});
    setOpen(true);
  };

  useEffect(() => {
    getScoreList();
  }, [queryParam]);

  return (
    <div className="ManageScore">
      <Form layout="inline" onFinish={(values) => setQueryParam({ ...initSearchParam, ...values })}>
        <Form.Item name="courseName" label="课程名称">
          <Input placeholder="请输入课程名称" />
        </Form.Item>
        <Form.Item name="className" label="班级名称">
          <Input placeholder="请输入班级名称" />
        </Form.Item>
        <Form.Item name="studentId" label="学生学号">
          <Input placeholder="请输入学生学号" />
        </Form.Item>

        <Form.Item>
          <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>

      <Space style={{ marginTop: 10, marginBottom: 10 }}>
        <Button type="primary" onClick={handleAddClass}>
          录入分数
        </Button>
      </Space>

      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          total,
          current: queryParam.current,
          pageSize: queryParam.pageSize,
          onChange: (current, pageSize) => setQueryParam({ ...queryParam, current, pageSize }),
        }}
      />

      <Modal
        title={title}
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <UpdateScore editScore={editScore} onCloseModal={handleCancel} ref={childRef} />
      </Modal>
    </div>
  );
};

export default ManageScore;
